<template>
  <div class="upload-box">

    <!--                        name就是文件上传的名字，要和后端接口的一样要不然会接受不到-->
    <!--                        data是携带的参数，后端接口要接受-->
    <!--                        action就是上传图片的接口-->
    <el-upload
        :action="updateUrl"
        :id="uuid"
        :class="['upload', drag ? 'no-border' : '']"
        :multiple="false"
        :show-file-list="false"
        :headers="uploadHeaders"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :drag="drag"
        :accept="fileType.join(',')"
        :data="uploadData"
    >

      <template v-if="modelValue">
        <img :src="modelValue" class="upload-image" />
        <div class="upload-handle" @click.stop>
          <div class="handle-icon" @click="editImg">
            <Edit />
            <span> 编辑   </span>
          </div>
          <div class="handle-icon" @click="imgViewVisible = true">
            <ZoomIn />
            <span> 查看 </span>
          </div>
          <div class="handle-icon" @click="deleteImg">
            <Delete />
            <span> 删除 </span>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="upload-empty">
          <slot name="empty">
<!--             <span>请上传图片</span>-->
            <el-icon>
              <Plus/>
            </el-icon>
          </slot>
        </div>
      </template>
    </el-upload>
    <div class="el-upload__tip">
      <slot name="tip"></slot>
    </div>
    <el-image-viewer
        v-if="imgViewVisible"
        @close="imgViewVisible = false"
        :url-list="[modelValue]"
    />
  </div>
</template>

<script lang="ts" setup>
import type { UploadProps } from 'element-plus'

import { generateUUID } from '@/utils'
import {ref, defineEmits, defineProps, defineOptions, reactive} from "vue";
import {getLocalstorage} from "@/utils/localStorage";
import {error, success} from "@/utils/tips";

defineOptions({ name: 'UploadImg' })

type FileTypes =
    | 'image/apng'
    | 'image/bmp'
    | 'image/gif'
    | 'image/jpeg'
    | 'image/pjpeg'
    | 'image/png'
    | 'image/svg+xml'
    | 'image/tiff'
    | 'image/webp'
    | 'image/x-icon'

// 接受父组件参数
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  updateUrl: {
    type: String,
    default: "http://127.0.0.1:5173/api/system/upload/uploadImg"
  },
  drag: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  fileSize: {
    type: Number,
    default: 5
  },
  fileType: {
    type: Array,
    default: () => ['image/jpeg', 'image/png', 'image/gif']
  },
  height: {
    type: String,
    default: '150px'
  },
  width: {
    type: String,
    default: '150px'
  },
  borderradius: {
    type: String,
    default: '8px'
  },
  type:{
    type:String,
    default:'aa',
    required:true
  }
})
//携带参数
const uploadData = reactive({
  prefix: props.type
})

// 生成组件唯一id
const uuid = ref('id-' + generateUUID())
// 查看图片
const imgViewVisible = ref(false)

const emit = defineEmits(['update:modelValue'])

const deleteImg = () => {
  emit('update:modelValue', '')
}

const uploadHeaders = ref({
  'Token':  getLocalstorage("Token"),
  'Shopid': 1
})

const editImg = () => {
  const dom = document.querySelector(`#${uuid.value} .el-upload__input`)
  dom && dom.dispatchEvent(new MouseEvent('click'))
}

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize
  const imgType = props.fileType
  if (!imgType.includes(rawFile.type as FileTypes))
    error('上传图片不符合所需的格式！')
  if (!imgSize) error(`上传图片大小不能超过 ${props.fileSize}M！`)
  return imgType.includes(rawFile.type as FileTypes) && imgSize
}

// 图片上传成功提示
const uploadSuccess: UploadProps['onSuccess'] = (res: any): void => {
  success('上传成功')
  emit('update:modelValue', res.data)
}

// 图片上传错误提示
const uploadError = () => {
  error('图片上传失败，请您重新上传！')
}
</script>
<style scoped lang="scss">
.is-error {
  .upload {
    :deep(.el-upload),
    :deep(.el-upload-dragger) {
      border: 1px dashed var(--el-color-danger) !important;

      &:hover {
        border-color: var(--el-color-primary) !important;
      }
    }
  }
}

:deep(.disabled) {
  .el-upload,
  .el-upload-dragger {
    cursor: not-allowed !important;
    background: var(--el-disabled-bg-color);
    border: 1px dashed var(--el-border-color-darker) !important;

    &:hover {
      border: 1px dashed var(--el-border-color-darker) !important;
    }
  }
}

.upload-box {
  .no-border {
    :deep(.el-upload) {
      border: none !important;
    }
  }

  :deep(.upload) {
    .el-upload {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: v-bind(width);
      height: v-bind(height);
      overflow: hidden;
      border: 1px dashed var(--el-border-color-darker);
      border-radius: v-bind(borderradius);
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);

        .upload-handle {
          opacity: 1;
        }
      }

      .el-upload-dragger {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        padding: 0;
        overflow: hidden;
        background-color: transparent;
        border: 1px dashed var(--el-border-color-darker);
        border-radius: v-bind(borderradius);

        &:hover {
          border: 1px dashed var(--el-color-primary);
        }
      }

      .el-upload-dragger.is-dragover {
        background-color: var(--el-color-primary-light-9);
        border: 2px dashed var(--el-color-primary) !important;
      }

      .upload-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .upload-empty {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        line-height: 30px;
        color: var(--el-color-info);

        .el-icon {
          font-size: 28px;
          color: var(--el-text-color-secondary);
        }
      }

      .upload-handle {
        position: absolute;
        top: 0;
        right: 0;
        display: flex;
        width: 100%;
        height: 100%;
        cursor: pointer;
        background: rgb(0 0 0 / 60%);
        opacity: 0;
        box-sizing: border-box;
        transition: var(--el-transition-duration-fast);
        align-items: center;
        justify-content: center;

        .handle-icon {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 0 6%;
          color: aliceblue;

          .el-icon {
            margin-bottom: 40%;
            font-size: 130%;
            line-height: 130%;
          }

          span {
            font-size: 85%;
            line-height: 85%;
          }
        }
      }
    }
  }

  .el-upload__tip {
    line-height: 18px;
    text-align: center;
  }
}
</style>
